package top.vanchor.flexible.config.initexception;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/4/3 20:49
 */
@ControllerAdvice(annotations = RestController.class)
@ResponseBody
@Log4j2
public class RestExceptionHandler {

    /**
     * 对于所有自定义的报错，都会被这个方法捕获
     *
     * @param e 异常
     * @return 返回异常信息
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public ExceptionResponse CustomizeExceptionHandler(Exception e) {
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            log.warn("【<Predictable> 可预见异常】：错误码{}，错误信息：{}", businessException.getCode(), businessException.getMessage());
            e.printStackTrace();
            return ExceptionResponse.create(businessException.getCode(), businessException.getMessage());
        } else {
            log.error(e.getMessage(), e);
            return ExceptionResponse.create(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
    }

    /**
     * 对于所有runtime的报错，都会被这个方法捕获
     *
     * @param e 异常
     * @return 返回异常信息
     */
    @ResponseBody
    @ExceptionHandler({Exception.class, RuntimeException.class})
    public ExceptionResponse runtimeExceptionHandler(Exception e) {
        //其他runtime的报错直接走UNEXPECTED_EXCEPTION
        log.error("【<Unexpected> 运行时异常】：" + e.getMessage(), e);
        return ExceptionResponse.exception(ErrorEnum.UNEXPECTED_EXCEPTION.getErrorCode(), ErrorEnum.UNEXPECTED_EXCEPTION.getErrorMsg(), e.toString());
    }

}